﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using CodeDynamiksEngine;
using MESCodeFile;

namespace mes_tublay
{
    public partial class frmBreakdown : Form
    {
        CodeScript script;
        CodeProcessor proc = new CodeProcessor(ThreadingMode.Normal);
        DataCache dat = new DataCache("myData");

        struct insertScript
        {
            public string appNumber;
            public string codeValue;
            public string serviceValue;
            public decimal feeValue;
            public decimal penalty;
        }

        frmDocumentsCheckList parent;
        string _myApplicationNumber = "";
        string _myDepartment = "";
        string _date;
        string office = "";
        List<string> chargesAndFees = new List<string>();
        int index = -1;
        int lastLength = -1;

        insertScript[] insScript = new insertScript[0];

        public frmBreakdown(frmDocumentsCheckList p, string applicationNumber, string dept, string date)
        {
            parent = p;
            _myApplicationNumber = applicationNumber;
            _myDepartment = dept;
            _date = date;
            InitializeComponent();
            this.Load += new EventHandler(frmBreakdown_Load);
            proc.ProcessCompleted += new EventHandler(proc_ProcessCompleted);
            txtServices.LostFocus += new EventHandler(txtServices_LostFocus);
            btnAdd.Click += new EventHandler(btnAdd_Click);
            btnSave.Click += new EventHandler(btnSave_Click);
            mnuRemove.Click += new EventHandler(mnuRemove_Click);
        }

        void mnuRemove_Click(object sender, EventArgs e)
        {
            if (grdBreakdown.SelectedRows.Count == 1)
            {
                if (grdBreakdown.SelectedRows[0].Index != -1)
                {
                    dat.SetActivePage(1);
                    dat.Delete(grdBreakdown.SelectedRows[0].Index);
                    txtTotal.Value = (decimal)formatAndGetTotal();
                }
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            Confirm.Question("Save Information", "Please double check your entries before saving.\r\n" +
                   "Do you wish to continue saving?");
            saveInformation();
        }

        void btnAdd_Click(object sender, EventArgs e)
        {
            //add value to grid
            if (txtCode.Text != "")
            {
                if (!DuplicateService())
                {
                    dat.SetActivePage(1);
                    dat.Insert(new object[] {txtCode.Text, txtServices.Text, txtFee.Value, txtPenalty.Value });

                    txtCode.Text = "";
                    txtServices.Text = "";
                    txtFee.Value = decimal.Parse("0.00");
                    txtPenalty.Value = decimal.Parse("0.00");
                    txtServices.Focus();

                    txtTotal.Value = (decimal)formatAndGetTotal();
                }
                else
                {
                    Confirm.Error("Duplicate Entry", "Duplicate Entry of Type of Service");
                }
            }
        }

        void txtServices_LostFocus(object sender, EventArgs e)
        {
            dat.SetActivePage(0);
            //int index = chargesAndFees.IndexOf(txtServices.Text.Trim());
            int index = txtServices.AutoCompleteCustomSource.IndexOf(txtServices.Text);
            if (index >= 0)
            {
                txtFee.Value = decimal.Parse(dat.GetValue(index, "fFee").ToString());
                //txtPenalty.Value = decimal.Parse(dat.GetValue(index, "fPenalty").ToString());
                txtCode.Text = dat.GetValue(index, "fCode").ToString();
                txtPenalty.Focus();
            }
            else
            {
                txtCode.Text = "";
                txtFee.Value = decimal.Parse("0.0");
                txtPenalty.Value = decimal.Parse("0.0");
                txtServices.Text = "";
            }
        }

        void proc_ProcessCompleted(object sender, EventArgs e)
        {
            proc.SafeCall(this, delegate { 
                if (proc.State == ProcessorFlag.Error ||
                        proc.State == ProcessorFlag.DataRdyErr ||
                        proc.State == ProcessorFlag.ReadyErr)
                    {
                        MessageBox.Show(proc.GetProcessorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        proc.ClearErrorFlag();
                        return;
                    }
                switch (proc.GetLastProcessName().ToString())
                {
                    case "SAVE":
                        parent.insertTotalValue(txtTotal.Value.ToString());
                        this.Close();
                        break;
                    case "LOAD":
                        proc.DataFetch(out dat);
                        dat.SetActivePage(0);
                        //auto complete
                        if (!txtServices.Focused)
                        {
                            //chargesAndFees.AddRange();
                            txtServices.AutoCompleteCustomSource.AddRange(dat.GetStringList(4));
                        }
                        txtServices.Enabled = true;
                        txtServices.Focus();

                        dat.SetActivePage(1);
                        grdBreakdown.DataSource = dat.ExportPage();
                        grdBreakdown.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;
                        grdBreakdown.Columns[2].DefaultCellStyle.Format = "#,#0.00";
                        grdBreakdown.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;
                        grdBreakdown.Columns[3].DefaultCellStyle.Format = "#,#0.00";

                        lastLength = dat.GetRecordCount(1);
                        //disable sorting mode
                        foreach (DataGridViewColumn column in grdBreakdown.Columns)
                        {
                            column.SortMode = DataGridViewColumnSortMode.NotSortable;
                        }

                        txtTotal.Value =(decimal)formatAndGetTotal();
                        

                        break;
                }

            });
        }

        void frmBreakdown_Load(object sender, EventArgs e)
        {
            txtServices.Enabled = false;
            lblDepartment.Text = "Department: " + _myDepartment;
            loadingInfo();
        }

        double formatAndGetTotal()
        {
            double total = 0;
            for (int i = 0; i < grdBreakdown.Rows.Count; i++)
            {
                double data = double.Parse(grdBreakdown.Rows[i].Cells[2].Value.ToString());
                double penalty = double.Parse(grdBreakdown.Rows[i].Cells[3].Value.ToString());
                total += data + penalty;
                

            }
            return total;
        }

        bool DuplicateService()
        {
            bool val = false;
            string data = "";
            for (int i = 0; i < grdBreakdown.Rows.Count; i++)
            {
                data = grdBreakdown.Rows[i].Cells[1].Value.ToString().ToLower();
                if (txtServices.Text.ToLower() == data)
                {
                    val = true;
                    i = grdBreakdown.Rows.Count;
                }
            }
                return val;
        }

        void saveInformation()
        {
            script = new CodeScript("SAVE");
            script.Add(CodeIns.DBU_NEW_CORE);
            script.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                    Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            script.Add(CodeIns.DBU_BEGIN_TRANSACTION);

            //delete previous records
            if (lastLength != 0)
            {
                script.Add(CodeIns.DBU_DELETE, "tblBusinessPermitFeesAndCharges", "fApplicationNumber = '" + _myApplicationNumber + "' AND fDepartment = '" + _myDepartment + "'");
            }
            //insert new records 
            for (int i = 0; i < grdBreakdown.Rows.Count; i++)
            {
                script.Add(CodeIns.DBU_INSERT, "tblBusinessPermitFeesAndCharges", new string[] { "fDate", "fApplicationNumber", "fDepartment", "fCode", "fTypeOfServices", "fFee", "fPenalty" },
                    new object[] {"'"+_date+"'","'"+_myApplicationNumber+"'", "'"+_myDepartment+"'", "'"+grdBreakdown.Rows[i].Cells[0].Value.ToString() +"'",
                        "'"+grdBreakdown.Rows[i].Cells[1].Value.ToString() +"'", "'"+double.Parse(grdBreakdown.Rows[i].Cells[2].Value.ToString()).ToString() +"'" , "'"+double.Parse(grdBreakdown.Rows[i].Cells[3].Value.ToString()).ToString() +"'" });
            }
            
            script.Add(CodeIns.DBU_END);
            proc.Run(script);

        }

        void loadingInfo()
        {
            CodeScript s = new CodeScript("LOAD");
            s.Add(CodeIns.DBU_NEW_CORE);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                    Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            s.Add(CodeIns.DBU_BEGIN_TRANSACTION);
            
            switch (_myDepartment)
            {
                case "MUNICIPAL HEALTH OFFICE": office = "MHO"; break;
                case "MUNICIPAL ENGINEERING OFFICE": office = "MEO"; break;
                case "FIRE DEPARTMENT": office = "FIRE_DEPARTMENT"; break;
                case "MUNICIPAL PLANNING AND DEVELOPMENT OFFICE": office = "MPDO"; break;
                case "MASSO": office = "MASSO"; break;
                case "PNP_TUBLAY": office = "PNP_TUBLAY"; break;
            }

            s.Add(CodeIns.DBU_QUERY, "SELECT * FROM tbldeptotherfeescharges WHERE fDepartment = '" + office + "'");
            s.Add(CodeIns.DBU_QUERY, "SELECT fCode AS 'Code', fTypeOfServices AS 'Type Of Services', fFee AS 'Amount', fPenalty AS 'Penalty' FROM tblBusinessPermitFeesAndCharges WHERE fApplicationNumber = '" + _myApplicationNumber + "' AND fDepartment = '"+_myDepartment+"'");

            s.Add(CodeIns.DBU_END);
            proc.Run(s);
        }
    }
}
